﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace Itfort.Web
{
	/// <summary>
	/// 相关WebControl控件扩展方法。
	/// </summary>
	public static class WebControlExtensions
	{
		/// <summary>
		/// 获取ListControl中被选中的项。
		/// </summary>
		/// <param name="cbl">ListControl实例对象。</param>
		/// <returns></returns>
		public static List<ListItem> GetSelectedItems(this ListControl cbl)
		{
			return cbl.Items.Cast<ListItem>().Where(p => p.Selected).ToList();
		}

		/// <summary>
		/// 获取ListControl中被选中的项的值。
		/// </summary>
		/// <param name="cbl">ListControl实例对象。</param>
		/// <returns></returns>
		public static string[] GetValues(this ListControl cbl)
		{
			return cbl.GetSelectedItems().Select(p => p.Value).ToArray();
		}

		/// <summary>
		/// 获取ListControl中被选中的项的值。
		/// </summary>
		/// <param name="cbl">ListControl实例对象。</param>
		/// <returns></returns>
		public static int[] GetInt32Values(this ListControl cbl)
		{
			return cbl.GetValues().Select(p => Int32.Parse(p)).ToArray();
		}

		/// <summary>
		/// 设置ListControl的选中项。
		/// </summary>
		/// <param name="cbl">ListControl实例对象。</param>
		/// <param name="values">需要设置选中的项的值。</param>
		public static void SetValues(this ListControl cbl, string[] values)
		{
			foreach (var value in values)
			{
				var item = cbl.Items.FindByValue(value);
				if (item != null)
				{
					item.Selected = true;
				}
			}
		}
	}
}
